//
//  AddBusineseLicenceViewController.m
//  PropertyManager
//
//  Created by TNG on 2018/8/15.
//  Copyright © 2018年 Tng. All rights reserved.
//

#import "AddBusineseLicenceViewController.h"

@interface AddBusineseLicenceViewController () <UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (strong, nonatomic) UITableView * tableview;
@property (nonatomic,copy) NSString * company;
@property (nonatomic,copy) NSString * name;
@property (nonatomic,copy) NSString * lincenceNum;
@property (nonatomic,copy) NSString * startTime;
@property (nonatomic,copy) NSString * endTime;
@property (strong, nonatomic) NSData * data;
@property (strong, nonatomic) UIImage * img;
@property (nonatomic,copy) NSString * startTimeStr;
@property (nonatomic,copy) NSString * endTimeStr;
@property (nonatomic,copy) NSString * sonCompanyName;
@property (nonatomic,copy) NSString * serviceName;
@property (nonatomic,copy) NSString * pkCustomerid;

@end

@implementation AddBusineseLicenceViewController

static NSString * PropertyReparisInputInfoTableViewCellID = @"PropertyReparisInputInfoTableViewCell";
static NSString * AddLincenceTimeTableViewCellID = @"AddLincenceTimeTableViewCell";
static NSString * AddBusineseLinenceImgTableViewCellID = @"AddBusineseLinenceImgTableViewCell";
static NSString * AddBusineseLinenceCommitTableViewCellID = @"AddBusineseLinenceCommitTableViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"上传营业执照";
    [self creatTableview];
    [self registCell];
}

-(void)registCell
{
    [self.tableview registerClass:[AddBusineseLinenceCommitTableViewCell class] forCellReuseIdentifier:AddBusineseLinenceCommitTableViewCellID];
    [self.tableview registerClass:[PropertyReparisInputInfoTableViewCell class] forCellReuseIdentifier:PropertyReparisInputInfoTableViewCellID];
    [self.tableview registerClass:[AddLincenceTimeTableViewCell class] forCellReuseIdentifier:AddLincenceTimeTableViewCellID];
    [self.tableview registerClass:[AddBusineseLinenceImgTableViewCell class] forCellReuseIdentifier:AddBusineseLinenceImgTableViewCellID];
}

-(void)creatTableview{
    if (self.tableview == nil) {
        UITableView * tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, kStatusAndNavBarH, WIDTH, HEIGHT - kStatusAndNavBarH - kHomeLineH) style:UITableViewStylePlain];
        tableview.delegate = self;
        tableview.dataSource = self;
        tableview.backgroundColor = SFMWhiteColor;
        if (@available(iOS 11.0, *)) {
            tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
        }
        self.tableview = tableview;
        [self.view addSubview:self.tableview];
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        return [UIView new];
    }
    
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
    line.backgroundColor = SFM242;
    
    UILabel * name = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, WIDTH- 40, 20)];
    name.font = font(14);
    name.textColor = SFM153;
    name.text = @"营业执照照片";
    name.textAlignment = NSTextAlignmentLeft;
    [line addSubview:name];
    
    return line;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        return 0.01;
    }
    return 40;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        if(indexPath.row == 6)
        {
            return 105;
        }else
        {
            return 55;
        }
    }else
    {
        if(indexPath.row == 0)
        {
            return 148;
        }else
        {
            return 75;
        }
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
    {
        return 7;
    }else
    {
        return 2;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        if(indexPath.row < 6)
        {
            PropertyReparisInputInfoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PropertyReparisInputInfoTableViewCellID];
            WeakSelf;
            if(indexPath.row == 0)
            {
                cell.titleLabel.text = @"用户主键";
                cell.textfiled.enabled = NO;
                cell.PropertyReparisInputInfoTableViewCellInputBlock = ^(NSString *text) {
                    weakSelf.pkCustomerid = text;
                };
                if (self.pkCustomerid != nil) {
                    cell.textfiled.text = self.pkCustomerid;
                }else
                {
                    cell.textfiled.placeholder = @"这是一个用户主键";
                }
            }else if (indexPath.row == 1)
            {
                cell.titleLabel.text = @"公司名称";
                cell.textfiled.enabled = NO;
                cell.PropertyReparisInputInfoTableViewCellInputBlock = ^(NSString *text) {
                    weakSelf.company = text;
                };
                if (self.company != nil) {
                    cell.textfiled.text = self.company;
                }else
                {
                    cell.textfiled.placeholder = @"这是一个公司名称";
                }
            }else if (indexPath.row == 2)
            {
                cell.titleLabel.text = @"分公司名称";
                cell.textfiled.enabled = NO;
                cell.PropertyReparisInputInfoTableViewCellInputBlock = ^(NSString *text) {
                    weakSelf.sonCompanyName = text;
                };
                if (self.sonCompanyName != nil) {
                    cell.textfiled.text = self.sonCompanyName;
                }else
                {
                    cell.textfiled.placeholder = @"这是一个分公司名称";
                }
            }else if (indexPath.row == 3)
            {
                cell.titleLabel.text = @"服务中心名称";
                cell.textfiled.enabled = NO;
                cell.PropertyReparisInputInfoTableViewCellInputBlock = ^(NSString *text) {
                    weakSelf.serviceName = text;
                };
                if (self.serviceName != nil) {
                    cell.textfiled.text = self.serviceName;
                }else
                {
                    cell.textfiled.placeholder = @"这是一个服务中心名称";
                }
            }else if (indexPath.row == 4)
            {
                cell.titleLabel.text = @"经营者姓名";
                cell.textfiled.enabled = NO;
                cell.PropertyReparisInputInfoTableViewCellInputBlock = ^(NSString *text) {
                    weakSelf.name = text;
                };
                if (self.name != nil) {
                    cell.textfiled.text = self.name;
                }else
                {
                    cell.textfiled.placeholder = @"请输入经营者姓名";
                }
            }else
            {
                cell.titleLabel.text = @"营业执照号码";
                cell.textfiled.placeholder = @"请输入营业执照号码";
                cell.PropertyReparisInputInfoTableViewCellInputBlock = ^(NSString *text) {
                    weakSelf.lincenceNum = text;
                };
            }
            return cell;
        }else
        {
            AddLincenceTimeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:AddLincenceTimeTableViewCellID];
            NSString * currentTime = [NSString currentTimeAndFormat:@"yyyy年MM月dd日"];
            if (self.startTime == nil) {
                self.startTime = currentTime;
                self.startTimeStr = [NSString currentTimeAndFormat:@"yyyy-MM-dd"];
            }
            [cell sendStartTIme:self.startTime AndEndTime:self.endTime];
            [cell.startTimeBtn addTarget:self action:@selector(startTimeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [cell.endTimeBtn addTarget:self action:@selector(endTimeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
    }else
    {
        if(indexPath.row == 0)
        {
            AddBusineseLinenceImgTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:AddBusineseLinenceImgTableViewCellID];
            [cell sendImage:self.img];
            [cell.img addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseImg)]];
            return cell;
        }else
        {
            AddBusineseLinenceCommitTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:AddBusineseLinenceCommitTableViewCellID];
            [cell.btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
    }
}

#pragma mark - 提交按钮
-(void)btnClick:(UIButton *)btn
{
    if (self.pkCustomerid == nil) {
        [SVProgressHUD ShowErrorMessage:@"请选择用户主键"];
        return;
    }
    
//    if (self.company == nil) {
//        [SVProgressHUD ShowErrorMessage:@"请选择公司名称"];
//        return;
//    }
//
//    if (self.sonCompanyName == nil) {
//        [SVProgressHUD ShowErrorMessage:@"请选择分公司名称"];
//        return;
//    }
//
//    if (self.serviceName == nil) {
//        [SVProgressHUD ShowErrorMessage:@"请选择服务中心名称"];
//        return;
//    }
//
//    if (self.name == nil) {
//        [SVProgressHUD ShowErrorMessage:@"请输入经营者姓名"];
//        return;
//    }
    
    if (self.lincenceNum == nil) {
        [SVProgressHUD ShowErrorMessage:@"请输入营业执照号码"];
        return;
    }
    
    if (self.startTimeStr == nil) {
        [SVProgressHUD ShowErrorMessage:@"请输入营业执照有效开始时间"];
        return;
    }
    
    if (self.endTimeStr == nil) {
        [SVProgressHUD ShowErrorMessage:@"请输入营业执照有效截止时间"];
        return;
    }
    
    btn.userInteractionEnabled = NO;
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setValue:self.company forKey:@"corpname"];
    [params setValue:self.name forKey:@"customername"];
    [params setValue:self.lincenceNum forKey:@"vcorplicensecode"];
    [params setValue:self.startTimeStr forKey:@"licensestartdate"];
    [params setValue:self.endTimeStr forKey:@"licenseenddate"];
    [params setValue:self.pkCustomerid forKey:@"pkCustomerid"];
    [params setValue:self.sonCompanyName forKey:@"fgsname"];
    [params setValue:self.serviceName forKey:@"servicecentre"];

    WeakSelf;
    btn.userInteractionEnabled = NO;
    dispatch_queue_t queue = dispatch_queue_create("netWork", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        NSString * url = [BASE_URL stringByAppendingString:@"/rest/zhyyzzController"];
        NSString * path = [url stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
        AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
        [manager.requestSerializer setValue:@"*/*" forHTTPHeaderField:@"Accept"];
        [manager.requestSerializer setValue:SFMToken forHTTPHeaderField:@"X-AUTH-TOKEN"];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html", nil];
        
        [manager POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            if(weakSelf.data!=nil)
            {
                NSString * fileName = @"fj";
                [formData appendPartWithFileData:weakSelf.data name:fileName fileName:@"fj.jpg" mimeType:@"image/jpeg"];
            }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary * dic = (NSDictionary *)responseObject;
            NSString * codeStr = [NSString stringWithFormat:@"%@",dic[@"respCode"]];
            if ([codeStr isEqualToString:@"0"]) {
                [SVProgressHUD ShowSuccessMessage:@"上传成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
            }else
            {
                [SVProgressHUD ShowErrorMessage:dic[@"respMsg"]];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                btn.userInteractionEnabled = YES;
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                btn.userInteractionEnabled = YES;
            });
        }];
    });
}

#pragma mark - 点击开始时间
-(void)startTimeBtnClick:(UIButton *)btn
{
    WeakSelf;
    ChooseDataTimeViewController * ctr = [[ChooseDataTimeViewController alloc] init];
    ctr.sendChooseTimeBlock = ^(NSDate *data) {
        NSDateFormatter *dateFormmater = [[NSDateFormatter alloc]init];
        [dateFormmater setDateFormat:@"yyyy年MM月dd日"];
        NSString * resultString = [dateFormmater stringFromDate:data];
        weakSelf.startTime = resultString;
        [dateFormmater setDateFormat:@"yyyy-MM-dd"];
        NSString * start = [dateFormmater stringFromDate:data];
        weakSelf.startTimeStr = start;
        [weakSelf.tableview reloadData];
    };
    [self.navigationController pushViewController:ctr animated:YES];
}

#pragma mark - 点击结束时间
-(void)endTimeBtnClick:(UIButton *)btn
{
    WeakSelf;
    ChooseDataTimeViewController * ctr = [[ChooseDataTimeViewController alloc] init];
    ctr.sendChooseTimeBlock = ^(NSDate *data) {
        NSDateFormatter *dateFormmater = [[NSDateFormatter alloc]init];
        [dateFormmater setDateFormat:@"yyyy年MM月dd日"];
        NSString * resultString = [dateFormmater stringFromDate:data];
        weakSelf.endTime = resultString;
        [dateFormmater setDateFormat:@"yyyy-MM-dd"];
        
        NSString * end = [dateFormmater stringFromDate:data];
        weakSelf.endTimeStr = end;
        [weakSelf.tableview reloadData];
    };
    [self.navigationController pushViewController:ctr animated:YES];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        WeakSelf;
        NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
        NSString *path=[docPath stringByAppendingPathComponent:@"person.archiver"];
        NSArray * arr =  [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        if (indexPath.row == 0) {
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"请选择用户主键" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            for (authListModel * model in arr) {
                UIAlertAction * action = [UIAlertAction actionWithTitle:model.pkCustomerid style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    weakSelf.pkCustomerid = model.pkCustomerid;
                    weakSelf.company = model.customername;
                    weakSelf.sonCompanyName = model.fgsname;
                    weakSelf.serviceName = model.servicecentre;
                    weakSelf.name = model.corpname;
                    [weakSelf.tableview reloadData];
                }];
                [alert addAction: action];
            }
            UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alert addAction: action1];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
}

#pragma mark -点击添加图片
- (void)chooseImg
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"选择" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    WeakSelf;
    UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = weakSelf;
        [strongSelf presentViewController:picker animated:YES completion:nil];
    }];
    
    UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf takePhoto];
    }];
    
    UIAlertAction * action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alert addAction: action1];
    [alert addAction: action2];
    [alert addAction: action3];
    
    [self presentViewController:alert animated:NO completion:nil];
}

#pragma  mark -开始拍照
-(void)takePhoto
{
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        //picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

#pragma mark -当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        self.img = image;
        if (UIImagePNGRepresentation(image) != nil)
        {
            self.data = UIImageJPEGRepresentation([UIImage newTry:image], qualityNum);
        }else
        {
            self.data=UIImageJPEGRepresentation(image, qualityNum);
        }
        [self.tableview reloadData];
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
